package model.repository

import androidx.compose.runtime.MutableState
import androidx.compose.runtime.snapshots.SnapshotStateList
import cn.hutool.core.util.IdUtil
import model.db.Db
import model.dto.AddFriendDTO
import model.dto.GroupDTO
import model.dto.ProcessApplyDto
import model.enums.NetworkSate
import model.network.Network
import model.vo.FriendNotificationItem
import model.vo.FriendsMappingItem
import model.vo.GroupMappingItem
import model.vo.SearchedItem
import ui.create_group.CreateGroupViewModel
import ui.home.HomeViewModel


/**
 * @author wei kunJie
 * @date 2024/4/16 16:06:04
 */
object ChannelMappingRepository {
    //已经是好友的或已经进入的群的account
    var channelMappingAccountList: MutableList<String> = mutableListOf()

    /**
     * 添加好友，发送好友申请
     */
    suspend fun addFriendApply(
        addFriendDTO: AddFriendDTO,
        networkState: MutableState<NetworkSate>,
        networkRMsg: MutableState<String>
    ) {
        try {
            val addFriend = Network.channelMappingService.addFriend(addFriendDTO)
            if (addFriend.code == 200) {
                //好友申请添加成功
                networkRMsg.value = "好友申请已经发送"
                networkState.value = NetworkSate.succeed
            } else {
                //发送申请的时候出错
                networkRMsg.value = "发送好友申请的时候出错"
                networkState.value = NetworkSate.failed
            }
        } catch (e: Exception) {
            //网络错误
            networkRMsg.value = "网络错误"
            networkState.value = NetworkSate.failed
            e.printStackTrace()
        }
    }

    /**
     * 全网查找好友、群聊
     */
    suspend fun searchChannelMapping(
        keyword: String,
        searchedItems: SnapshotStateList<SearchedItem>,
        searchBtnEnabled: MutableState<Boolean>
    ) {
        try {
            val searchChannelMapping = Network.channelMappingService.searchChannelMapping(keyword)
            if (searchChannelMapping.code == 200) {
                searchedItems.clear()
                searchChannelMapping.data?.let { searchedItems.addAll(it) }
            }
            println(searchChannelMapping.msg)
        } catch (e: Exception) {
            //网络错误
            e.printStackTrace()
        } finally {
            searchBtnEnabled.value = true
        }
    }

    /**
     * 处理申请记录
     */
    suspend fun processFriendRequest(
        processApplyDto: ProcessApplyDto,
        friendAccount: String,
        homeViewModel: HomeViewModel
    ) {
        try {
            val processFriendRequest = Network.channelMappingService.processFriendRequest(processApplyDto)
            if (processFriendRequest.code == 200) {
                //获取好友信息
                getFriendByAccount(friendAccount, homeViewModel)
                //更新UI
                homeViewModel.friendNotificationItems.forEach {
                    if (it.id == processApplyDto.applyId) {
                        it.applyState = processApplyDto.state.toString()
                        Db.updateFriendNotice(processApplyDto)
                    }
                }
                val list = mutableListOf<FriendNotificationItem>()
                list.addAll(homeViewModel.friendNotificationItems)
                homeViewModel.friendNotificationItems.clear()
                homeViewModel.friendNotificationItems.addAll(list)
            }
            println(processFriendRequest.msg)
        } catch (e: Exception) {
            //网络错误
            e.printStackTrace()
        }
    }

    suspend fun getFriendByAccount(account: String, homeViewModel: HomeViewModel) {
        try {
            val friendByAccount = Network.channelMappingService.getFriendByAccount(account)
            if (friendByAccount.code == 200) {
                val userVo = friendByAccount.data
                val friendsMappingItem = FriendsMappingItem(
                    account = userVo?.account.toString(),
                    userName = userVo?.username.toString(),
                    headUrl = userVo?.avatar.toString(),
                    state = "[未知]",
                    personalSignature = "暂无个性签名",
                    userVo = userVo
                )
                Db.saveFriend(friendsMappingItem)
                homeViewModel.friendsMappingItems.add(friendsMappingItem)
                channelMappingAccountList.add(friendsMappingItem.account)
            }
            println(friendByAccount.msg)
        } catch (e: Exception) {
            //网络错误
            e.printStackTrace()
        }
    }

    suspend fun createGroup(createGroupViewModel: CreateGroupViewModel, homeViewModel: HomeViewModel) {
        val groupDTO = GroupDTO()
        groupDTO.groupName =
            UserRepository.user?.username + "、" + createGroupViewModel.choseFriendList[0].userName + "等的群聊"
        groupDTO.userAccounts = createGroupViewModel.choseFriendList.map { it.account }
        groupDTO.userAccounts = groupDTO.userAccounts!! + listOf(UserRepository.user?.account.toString())
        groupDTO.groupAvatar=""
        try {
            val createGroup = Network.channelMappingService.createGroup(groupDTO)
            if (createGroup.code == 200) {
                val groupVO = createGroup.data
                //创建群聊成功
                createGroupViewModel.isShow.value = false
//                val groupMappingItem = GroupMappingItem(
//                    id = IdUtil.getSnowflakeNextId(),
//                    groupHeadUrl = groupVO?.groupAvatar.toString(),
//                    groupName = groupVO?.groupName.toString(),
//                    groupAccount = groupVO?.groupAccount.toString()
//                )
//                homeViewModel.groupMappingItems.add(groupMappingItem)
                //持久化
//                Db.saveGroup(groupMappingItem)
//                groupVO?.userVoList?.forEach {
//                    Db.saveGroupUser(groupMappingItem.groupAccount,it)
//                }
            } else {
                createGroupViewModel.createClickEnable.value = true
            }
            println(createGroup.msg)
        } catch (e: Exception) {
            //网络错误
            createGroupViewModel.createClickEnable.value = true
            e.printStackTrace()
        }
    }
}